<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
      + path + "/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="<%=basePath%>">
<!-- 下拉框 -->
<link rel="stylesheet" href="static/ace/css/chosen.css" />

<link href="plugins/kindeditor/themes/simple/simple.css" type="text/css" rel="stylesheet">
<link rel="stylesheet" href="static/ace/css/datepicker.css" />
<link href="//cdn.bootcss.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet">
<!-- jsp文件头和头部 -->
<%@ include file="../index/top.jsp"%>
<style>
.disabled{color:#000;cursor: default;}
.disabled:hover{color:#000;text-decoration:none;}
</style>
</head>
<body class="no-skin">
  <!-- /section:basics/navbar.layout -->
  <div class="main-container" id="main-container">
    <!-- /section:basics/sidebar -->
    <div class="main-content">
      <div class="main-content-inner">
        <div class="page-content">
          <div class="row">
            <div class="col-xs-12">
              <form action="period/updateGoodsTime.do" name="goodsForm" id="goodsForm" method="post">
               <input type="hidden" name="timeId" id="timeId" value="${pd.timeId }" />
                <div id="zhongxin" style="padding-top: 13px;">
                  <table id="table_report"
                    class="table table-striped table-bordered table-hover">
                    <tr>
                      <td style="width: 79px; text-align: right; padding-top: 13px;">基地:&emsp;</td>
                      <td><input type="text" readonly="readonly"
                         value="${goods.name }"
                        maxlength="100" style="width: 98%;" /></td>
                    </tr>
                    <tr>
                      <td style="width: 79px; text-align: right; padding-top: 13px;"> 期次:&emsp;</td>
                      <td><input type="text" readonly="readonly"
                         value="${goods.time }"
                        maxlength="100"
                        style="width: 98%;" /></td>
                    </tr>
                    <tr>
                        <td style="width: 79px; text-align: right; padding-top: 13px;">零售价:&emsp;</td>
                        <td><input type="text" name="price" id="price" value="${goods.price }"
                        maxlength="32" placeholder="这里输入零售价" title="零售价"
                        style="width: 98%;" /></td>
                    </tr>
                    <tr>
                      <td style="width: 79px; text-align: right; padding-top: 13px;"> 标题:&emsp;</td>
                      <td><input type="text" name="title" id="title" value="${goods.title }"
                        maxlength="100" placeholder="这里输入标题" title="标题"
                        style="width: 98%;" /></td>
                     </tr>
                    <tr>
                        <td style="width: 79px; text-align: right; padding-top: 13px;">关键字:&emsp;</td>
                        <td><input type="text" name="keyword"  id="keyword" value="${goods.keyword }"
                        maxlength="32" placeholder="这里输入关键字" title="关键字"
                        style="width: 98%;" /></td>
                    </tr>
                    <tr>
                      <td style="width: 79px; text-align: right; padding-top: 13px;">描述:&emsp;</td>
                      <td><textarea rows="5" cols="10" id="describe" name="describe" maxlength="250"
                          style="width: 99%;" title="商品描述">${goods.describe }</textarea></td>
                    </tr>
                  
                    <tr>
                      <td  style="width: 79px; text-align: right; padding-top: 13px;">售卖单位:&emsp;</td>
                      <td><select
                        class="dib"
                        name="unit" id="unit"
                        data-placeholder="售卖单位"
                        style="vertical-align: top;width:98%;">
                          <c:forEach var="co" varStatus="i" items="${unit}">
                          <c:if test='${co.type =="00"}'>
                            <option value="${co.unit }" <c:if test='${goods.unit == co.unit}'>selected=selected</c:if>> ${co.name}</option>
                          </c:if>
                          </c:forEach>
                      </select>
                      </td>
                      </tr>
                    <tr>
                      <td  style="width: 79px; text-align: right; padding-top: 13px;">收获单位:&emsp;</td>
                      <td><select
                        class="dib"
                        name="harvest_unit" id="harvest_unit"
                        data-placeholder="收获单位"
                        style="vertical-align: top;width:98%;">
                          <c:forEach var="co" varStatus="i" items="${unit}">
                          <c:if test='${co.type =="01"}'>
                            <option value="${co.unit }"
                              <c:if test='${goods.unit == co.unit}'>selected=selected</c:if>>
                              ${co.name}</option>
                           </c:if>
                          </c:forEach>
                      </select>
                      </td>
                      </tr>
                      <tr>
                      <td
                        style="width: 79px; text-align: right; padding-top: 13px;">销售时间:</td>
                      <td><span class="dib vm">上架时间:&nbsp;</span><input
                        id="start_time" name="start_time"
                        placeholder="请选择上架时间"
                        value="${goods.start_time }" />&emsp;&emsp; <span
                        class="dib vm">下架时间 :&nbsp;</span><input
                        class="dib vm" id="end_time" name="end_time"
                        placeholder="请选择下架时间 " value="${goods.end_time }" /></td>
                    </tr>
                    <tr>
                      <td
                        style="width: 79px; text-align: right; padding-top: 13px;">缩略图:</td>
                      <td><a href="javascript:void(0)"
                        class="onePicUpload">上传图片</a> <c:if
                          test="${not empty goods.thumb}">
                          <a href='${goods.thumb }' target='_blank'><img
                            src='${goods.thumb }' width='80' height='50' /></a>
                        </c:if> <input type="hidden" name="thumb" id="thumb"
                        value="${goods.thumb }" /></td>
                    </tr>

                    <tr>
                      <td
                        style="width: 79px; text-align: right; padding-top: 13px;">展示图片:</td>
                      <td><a href="javascript:void(0)"
                        class="picFileUpload">上传图片</a> <input
                        type="hidden" id="picture" name="picture" id="picture"
                        value="${goods.picture }" /></td>
                    </tr>
                    <tr>
                      <td
                        style="width: 79px; text-align: right; padding-top: 13px;">商品详情:</td>
                      <td>
                          <textarea class="content" style="width: 1050px; height: 300px;"
                          name="content" id="content">${goods.content}</textarea>
                          </td>
                    </tr>
                    
                  </table>
                   <table id="table_report1"
                    class="table table-striped table-bordered table-hover">
                       <tr>
                        <td style="text-align: center;" colspan="10">
                        <c:if test="${state!=00 }">
                          <a class="btn btn-mini btn-primary"
                          onclick="save();">保存</a>
                        </c:if>
                           <a class="btn btn-mini btn-danger"
                          onclick="top.Dialog.close();">取消</a>
                        </td>
                      </tr>
                    </table>
                </div>
                <div id="zhongxin2" class="center" style="display: none">
                  <br /> <br /> <br /> <br /> <img
                    src="static/images/jiazai.gif" /><br />
                  <h4 class="lighter block green"></h4>
                </div>
              </form>
            </div>
            <!-- /.col -->
          </div>
          <!-- /.row -->
        </div>
        <!-- /.page-content -->
      </div>
    </div>
    <!-- /.main-content -->
  </div>


  <!-- /.main-container -->
  <!-- basic scripts -->
  <!-- 页面底部js¨ -->
  <%@ include file="../index/foot.jsp"%>
  <!-- ace scripts -->
  <script src="static/ace/js/ace/ace.js"></script>
  <!-- inline scripts related to this page -->
  <script src="static/ace/js/bootbox.js"></script>
  <!-- 下拉框 -->
  <script src="static/ace/js/chosen.jquery.js"></script>
  <!--提示框-->
  <script type="text/javascript" src="static/js/jquery.tips.js"></script>
  <script type="text/javascript" src="static/js/common/file_upload.js"></script>
  <script type="text/javascript" src="plugins/kindeditor/kindeditor-all.js"></script>
  <script type="text/javascript" src="plugins/kindeditor/lang/zh_CN.js"></script>
  <script type="text/javascript" src="static/laydate/laydate.js"></script>
  <script type="text/javascript" src="static/js/provincial.municipal.league.js"></script>
</body>
<script type="text/javascript">
  $(top.hangge());
  var itemAddEditor ;
  var currentIndex = 0;
  //页面初始化完毕后执行此方法
  var min_ratio=$("#min_ratio").val();
  var max_ratio=$("#max_ratio").val();
  
  $(function(){
    
    
    SpecificationsBtn();
    //创建富文本编辑器
    TAOTAO.kingEditorParams = {
      //指定上传文件参数名称
      filePostName  : "uploadFile",
      //指定上传文件请求的url。
      uploadJson : '<%=basePath%>pic/upload',
      //上传类型，分别为image、flash、media、file
      dir : "image",
      extraFileUploadParams:{isCom:"01",width:800,height:800,quality:0.8,end:"view"}
    }
    
    TAOTAO.kingEditorAutoParams = {
        //指定上传文件参数名称
        filePostName  : "uploadFile",
        //指定上传文件请求的url。
        uploadJson : '<%=basePath%>pic/upload',
        //上传类型，分别为image、flash、media、file
        dir : "image",
        extraFileUploadParams:{isCom:"01",width:200,height:200,quality:1,end:"thumb"}
      }
    
    goodsAddEditor = TAOTAO.createEditor("#goodsForm [name=content]");
    //初始化类目选择和图片上传器
    TAOTAO.initPicUpload($("input[name=picture]").val());
    TAOTAO.initOnePicUpload($("input[name=thumb]").val());
    $('body').on('click','.imageButton',function(){
      var id=$("#id").val();
      var picture=$("#picture").val();
      var imgsrc=$(this).parent('li').find("img").attr("src");
      var _this = $(this);
      var newPicture="";
      if(picture.indexOf((imgsrc+',')) >-1){
        newPicture=picture.replace((imgsrc+','),'');
      }else if(picture.indexOf((','+imgsrc)) > -1){
        newPicture=picture.replace((','+imgsrc),'');
      }
      $.ajax({
        url:"<%=basePath%>pic/pictureDelete",
        type:"post",
        async:true,
        dataType:"text",
        data:{"id":id,"newPicture":newPicture,"imgsrc":imgsrc},
        success : function(data) {
          if(data != null){
            _this.parent('li').remove();
            $("#picture").val(newPicture);
          }
          alert(message);
        },error : function(XMLHttpRequest, textStatus){
          alealert(textStatus);
        }
      });   
    });
  });
  $("#costPrice").change(function(){
    $("#agentPrice").val(($(this).val()*1.1).toFixed(2));
  });
  $("#price").change(function(){
    if($("#isSales").val()=='00'||'${msg}'=='saveG'){
      $("#realPrice").val($(this).val());
    }
  });
  
  $("#isSales").change(function(){
    var tempPrice=$("#tempPrice").val();
    if($(this).val()=='00'&&'${msg}'=='editG'){
      $("#realPrice").val($("#price").val());
    }else if($(this).val()=='01'&&'${msg}'=='editG'){
      $("#realPrice").val(tempPrice);
    }
    
  });
  
 $('body').on('click',function(){

	 
 })
 
 
 
 function close(){
	 var parent = $(window.parent.document)
	 var mainFrame = parent.find('#mainFrame')
	 var page = mainFrame[0].contentWindow.document
	 var page_z56 = $(page).find('#page_z56')[0]
	 var iframes = $(window.parent.document).find('iframe')
	 var len = iframes.length-1
	 parent.find('#_DialogBGDiv').remove()
	 for(var i=0;i<len;i++){
		 var dd = parent.find('#_DialogDiv_'+i);
		 dd.remove()
	 }
	// 刷新页面
	 page_z56.contentWindow.document.location.reload()
	 
	 
 }
 
 
  function save(){
	  
	   if($.trim($("#price").val())==""){
            alert("请输入商品零售价");
            return false;
    	}
	  	if($.trim($("#title").val())==""){
	          alert("请输入商品标题");
	          return false;
	    }
	   	if($.trim($("#keyword").val())==""){
	          alert("请输入商品关键字");
	          return false;
	    }
		if($.trim($("#describe").val())==""){
	          alert("请输入商品描述");
	          return false;
	    }
		if($.trim($("#start_time").val())==""){
	          alert("请选择上架时间");
	          return false;
	    }
		if($.trim($("#end_time").val())==""){
	          alert("请选择下架时间");
	          return false;
	    }
        if($.trim($("#thumb").val())==""){
            alert("请上传商品缩略图");
            return false;
        }
        if($.trim($("#picture").val())==""){
            alert("请上传商品展示图");
            return false;
        }
        if(goodsAddEditor.isEmpty()){
      	   alert("请上传商品展示图");
           return false;
        } 
        goodsAddEditor.sync(); 
        $("#goodsForm").submit();
        $("#zhongxin").hide();
        $("#zhongxin2").show(); 
  }
  
  
  // 获取商品Id
  
  var items = $('.bingGoodsId');
  var gId=[];
  for(var i=0;i<items.length;i++){
	  var id = items.eq(i).attr('data-id');
	  gId.push({
		  key:id,
		  value:''
	  })
  }

  function bindingGoods(specId){
	var timeId= $("#timeId").val();
	var goodsId= $("#goodsId").val();
	var baseId= $("#base_id").val();
	
	  var diag = new top.Dialog();
	     diag.Drag=true;
	     diag.Title ="绑定区域商品";
	     diag.URL = '<%=basePath%>period/bindingGoods.do?specId='+specId+'&baseId='+baseId;
	    diag.Width = 700;
	    diag.Height = 400;
	    diag.CancelEvent = function() {
	      diag.close();
	    }, diag.OKEvent = function() {
	      var goodsSpec= $("#goodsSpec").val()
	      goodsSpec = goodsSpec.slice(1,-1).split(',')
	      var child = diag.innerFrame.contentWindow.document;
	      var countId=$(child).find("#ids").val();
	      for(var i=0;i<gId.length;i++){
	  		var item = gId[i];
	  		var id = item.key;
	  		if(specId == id){
	  			item.value=countId
	  		}	
	  	}
	      $("#countId").val(JSON.stringify(gId));
	      alert("区域商品绑定成功，请插入期次!")
	      $(".eper").show()
	      diag.close();
	    };//点击确定后调用的方法
	    diag.show();
  }
  
  function editGoodsTime(specId){
	  var countId='';
	 var goodsId=$("#goodsId").val();
	 var timeId=$("#timeId").val();
	 var count=$("#countId").val();
	 var obj =eval(count);
	 for(var i=0;i<obj.length;i++){
  		var item = obj[i];
  		var id = item.key;
  		if(specId == id){
  			countId=item.value;
  		}	
	 }
	 window.location.href='<%=basePath%>period/goodsSpecTime.do?countId='+countId+'&goodsId='+goodsId+'&timeId='+timeId+'&specId='+specId;
  }
  
  
  $(".chooseClass").on("click",function(){
     var diag = new top.Dialog();
     diag.Drag=true;
     diag.Title ="修改";
     diag.URL = '<%=basePath%>classify/toClassifyPage.do';
    diag.Width = 500;
    diag.Height = 500;
    diag.CancelEvent = function() {
      diag.close();
    }, diag.OKEvent = function() {
      var child = diag.innerFrame.contentWindow.document;
      $("#classId").val($(child).find("#classId").val());
      $("#className").html($(child).find("#className").val());
      diag.close();
    };//点击确定后调用的方法
    diag.show();
  })
  
  
  function getInputVal($parent){
 		  var $table = $parent.find('.js-goods-standard');
 		  var ths = $table.find('thead th')
 		  var trs = $table.find('tbody tr')
 		  var html=''
 		  var data=[{
 			 key:[],
 			 value:[]
 		  }]
 		  for(var i=1;i<ths.length;i++){
 			  var val = ths.eq(i).text()
 			  data[0].key.push(val)
 		  } 		  
    	  for(var i=0;i<trs.length;i++){
    		  var tds = trs.eq(i).find('td')
    		  var text ='';
    		  data[0].value.push([])
    		  for(var j=1;j<tds.length;j++){
    			  var val =tds.eq(j).find('input[name=stock]').val()
    			  var index = tds.eq(j).attr('data-index')
    			  if(index){
    				  if(j === tds.length-2){
    					  text +=index
    				  }else{
    					  text +=index+'-'
    				  }
    			  }
    			  if(!!val){
    				  data[0].value[i].push($.trim(val));
    			  }
    			 
    		  }
    		  data[0].value[i].push(text);
    	  }
    	  var data=JSON.stringify(data);
    	 //$("#param").val(data);
    	 
    	 return data;
 	  }
  
  
   $("#selectSpec").on("click",function(){
	   if($(this).hasClass('disabled')){
		   return false;
	   }
	 var $this = $(this);
     var diag = new top.Dialog();
     diag.Drag=true;
     diag.Title ="添加规格";
     diag.URL = '<%=basePath%>goods/toGoodsSpec.do';
     diag.Width = 1200;
     diag.Height = 500;
     diag.CancelEvent = function() {
     diag.close();
    }, diag.OKEvent = function() {
      var child = diag.innerFrame.contentWindow.document;
      //[{"key":["规格1","库存"],"value":[["1","p1"]]}]
      
      var param = getInputVal($(child))
      
      var attr=$(child).find("#attr").val();
      //var param=$(child).find("#param").val();
      
      console.log(param)
      
      if(attr !="" &&param != ""){
        $("#attr").val(attr);
        $("#param").val(param)
        $("#gS").html("已添加")
        $this.addClass('disabled')
      }
      diag.close();
    };//点击确定后调用的方法
    diag.show();
  })
  
  
  
  
  $("#selectUnitSpan").on("click",function(){
	  	 var $this = $(this);
	     var isSelectUnit = $this.find("input").val();
	     if(isSelectUnit == '00'){
	    	 $this.find("input").prop("checked",true); 
	      }else{
	    	 $this.find("input").prop("checked",false); 
	      }
	     var diag = new top.Dialog();
	     diag.Drag=true;
	     diag.Title ="多单位设置";
	     diag.URL = '<%=basePath%>goods/unit.do';
	     diag.Width = 500;
	     diag.Height = 500;
	     diag.CancelEvent = function() {
	      diag.close();
	      if(isSelectUnit == '00'){
	    	  $this.find("input").prop("checked",false); 
	      }else{
	    	  $this.find("input").prop("checked",true); 
	      }
	    }, diag.OKEvent = function() {
	      var child = diag.innerFrame.contentWindow.document;
	      diag.close();
	    };//点击确定后调用的方法
	    diag.show(); 
	  
  })
  
  //decimal类型判断
  function isDecimal(item) {
    var obj = $(item);
    if (obj.length > 0) {
      if ($(obj).val() != null && typeof ($(obj).val()) != "undefined") {
        var str = $(obj).val().toString();
        if (str != "") {
          var pattern = '^-?[1-9]\\d*$|^-?0\\.\\d*$|^-?[1-9]\\d*\\.\\d*$';
          var reg = new RegExp(pattern, 'g');
          if (reg.test(str)) {
            return true;
          } else {
            if (str.match(/[^0-9\.-]/g) != null) {
              if (str.match(/[^0-9\.-]/g).length > 0) {
                $(item).val('');
              }
            }
          }
        }
      }
    }
    return false;
  }
  //检查是否为正整数
  function isInt(a) {
    var reg = /^\d+$/;
    return reg.test(a);
  }
  var SpecificationsBtn = function() {
    $(".SpecificationsBtn").on("click", function() {

    })
  }
  //检查输入对象的值是否符合整数格式
  function isInteger(str) {
    var regu = /^[-]{0,1}[0-9]{1,}$/;
    return regu.test(str);
  }

  var removeImg = function() {

  }

  function toDecimal(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
      return;
    }
    f = Math.round(x * 100) / 100;
    return f;
  }

  function addTr(tr) {
    var type = $("#isAdvanceState").val();
    if (type == '01') {
      $('.advanceEle').show()
      $('.payment').show()
    } else {
      $('.advanceEle').hide()
      $('.payment').hide()
    }
  }


  var startTime = {
    elem : '#start_time',
    format : 'YYYY-MM-DD hh:mm:ss',
    min : laydate.now(), //设定最小日期为当前日期
    max : '2099-06-16 23:59:59', //最大日期
    istime : true,
    istoday : true,
    choose : function(datas) {
      endTime.min = datas; //开始日选好后，重置结束日的最小日期
      endTime.start = datas //将结束日的初始值设定为开始日
    }
  };

  var endTime = {
    elem : '#end_time',
    format : 'YYYY-MM-DD hh:mm:ss',
    min : laydate.now(),
    max : '2099-06-16 23:59:59',
    istime : true,
    istoday : true,
    choose : function(datas) {
      startTime.max = datas; //结束日选好后，重置开始日的最大日期
    }
  };
  
  laydate(startTime);
  laydate(endTime);
</script>
</html>